﻿using System.Collections.Generic;

namespace ProblemsSet
{
    public class Problem_50 : BaseProblem
    {
        public override object GetResult()
        {
            const int max = 1000000;

            var val = MathLogic.GetPrimeList(max, true);
            var hs = new HashSet<long>(val);
            var mxCnt = 0;
            long mxPrm = 0;

            var summs = new List<long>(val.Count) {0};
            foreach (var h in val)
            {
                summs.Add(summs[summs.Count-1]+h);
            }

            for (var i = 0; i < summs.Count - 1; i++ )
            {
                for (var j = i+mxCnt+1; j < summs.Count; j++)
                {
                    var q = summs[j] - summs[i];
                    if (q > max) break;
                    if (!hs.Contains(q)) continue;
                    if (mxCnt >= j - i + 1) continue;
                    mxCnt = j - i + 1;
                    mxPrm = q;
                }
            }

            return mxPrm;
        }

        public override string Problem
        {
            get
            {
                return @"The prime 41, can be written as the sum of six consecutive primes:

41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.

The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.

Which prime, below one-million, can be written as the sum of the most consecutive primes?";
            }
        }

        public override bool IsSolved
        {
            get
            {
                return true;
            }
        }

        public override object Answer
        {
            get
            {
                return 997651;
            }
        }

    }
}
